package info.mikrotubula.validators;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class EmailValidator implements Validator {

    private static final String EMAIL_REGEX = "^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,4})+$";
    
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
      Pattern mask =  Pattern.compile(EMAIL_REGEX);
      String emailField = (String)value; 
      Matcher matcher = mask.matcher(emailField);
	     
    if (!matcher.matches()){
	     	
       FacesMessage message = new FacesMessage();
       message.setDetail("Błędny adres email");
       message.setSummary("Email: Błędny adres email");
       message.setSeverity(FacesMessage.SEVERITY_ERROR);
       
       throw new ValidatorException(message);
    }
      
 }

    
}
